package v1

import (
	"sweetsunnyflower/app/models/user_blacklist"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type UserBlacklistsController struct {
	Controller
}

func (ctrl *UserBlacklistsController) Index(c *gin.Context) {
	userID := auth.CurrentIntUID(c)
	userBlacklists := user_blacklist.GetUserBlacklists(userID)
	response.Data(c, userBlacklists)
}

func (ctrl *UserBlacklistsController) Store(c *gin.Context) {

	request := requests.UserBlacklistRequest{}
	if ok := requests.Validate(c, &request, requests.UserBlacklistSave); !ok {
		return
	}

	user := auth.CurrentUser(c)

	user.Blacks = user.Blacks + 1
	user.Save()

	userBlacklistModel := user_blacklist.UserBlacklist{
		UserID:  user.ID,
		BlackID: request.BlackID,
	}
	userBlacklistModel.Create()
	if userBlacklistModel.ID > 0 {
		response.Created(c, userBlacklistModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *UserBlacklistsController) Delete(c *gin.Context) {

	userBlacklistModel := user_blacklist.Get(c.Param("id"))

	if userBlacklistModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyUserBlacklist(c, userBlacklistModel); !ok {
		response.Abort403(c)
		return
	}

	user := auth.CurrentUser(c)

	user.Blacks = user.Blacks - 1

	user.Save()

	rowsAffected := userBlacklistModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
